package com.wsoft.oss.config;

import com.wsoft.oss.service.IOssService;
import com.wsoft.oss.service.impl.OssLocalServiceImpl;
import com.wsoft.oss.service.impl.OssMinioServiceImpl;
import com.wsoft.oss.utils.MinioTemplate;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

/**
 * 文件上传 配置类
 *
 * @Author z001
 * @Date 2024/9/26 10:38
 */
@Configuration
@EnableConfigurationProperties(MinioProperties.class)
public class FileConfig {

    public static final String TYPE_MINIO = "minio";

    public static final String TYPE_LOCAL = "local";

    /**
     * 初始化 minioClient
     */
    @Bean
    @ConditionalOnProperty(prefix = "file", name = {"type"}, havingValue = TYPE_MINIO)
    public MinioClient minioClient(MinioProperties p) throws Exception {
        MinioClient client = MinioClient.builder()
                .endpoint(p.getEndpoint())
                .credentials(p.getAccessKey(), p.getSecretKey())
                .build();
        if (!client.bucketExists(BucketExistsArgs.builder().bucket(p.getBucketNamePublic()).build())) {
            client.makeBucket(MakeBucketArgs.builder().bucket(p.getBucketNamePublic()).build());
        }
        if (!client.bucketExists(BucketExistsArgs.builder().bucket(p.getBucketNameLogin()).build())) {
            client.makeBucket(MakeBucketArgs.builder().bucket(p.getBucketNameLogin()).build());
        }
        if (!client.bucketExists(BucketExistsArgs.builder().bucket(p.getBucketNameAuthority()).build())) {
            client.makeBucket(MakeBucketArgs.builder().bucket(p.getBucketNameAuthority()).build());
        }
        return client;
    }

    @Bean
    @ConditionalOnProperty(name = "file.type", havingValue = TYPE_MINIO)
    @DependsOn(value = "minioClient")
    public MinioTemplate minioTemplate() {
        return new MinioTemplate();
    }


    /**
     * 初始化 Minio service
     * @return IOssFileService
     */
    @Bean
    @ConditionalOnProperty(name = "file.type", havingValue = TYPE_MINIO)
    @DependsOn(value = "minioTemplate")
    public IOssService initMinioFileService() {
        return new OssMinioServiceImpl();
    }


    /**
     * 初始化 Local service
     * @return IOssFileService
     */
    @Bean
    @ConditionalOnProperty(name = "file.type", havingValue = TYPE_LOCAL)
    public IOssService initLocalFileService() {
        return new OssLocalServiceImpl();
    }

}
